package com.dbapp.garden.controller.staff;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.dbapp.garden.config.security.PermissionUser;
import com.dbapp.garden.entity.*;
import com.dbapp.garden.service.*;
import com.dbapp.garden.vm.StaffInfoSearchVm;
import com.dbapp.garden.vo.GardenStaffInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.dbapp.garden.common.DataTableUtils;
import com.dbapp.garden.common.RenderJSON;
import com.dbapp.garden.vm.GardenStaffInfoVm;

@Controller
public class GardenStaffInfoController {
    @Autowired
    private GardenStaffInfoService gardenStaffInfoService;

    @Autowired
    private GardenStudentStateService stateService;

    @Autowired
    private GardenStaffPositionService positionService;

    @Autowired
    private GardenDepartmentService deptService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysRoleUserService roleUserService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @GetMapping("/staff")
    @PreAuthorize("hasAuthority('PERMISSION_STAFF')")
    public String toGardenStaffPage(Model model,@SessionAttribute("user") PermissionUser user) {

        Map<String, Object> paramMap = new HashMap<String, Object>(16);
        paramMap.put("gardenId", user.getGardenId());
        List<GardenStaffPosition> positions = positionService.getPositionList(paramMap);
        List<GardenDepartment> departments = deptService.getDepartmentList(paramMap);


        model.addAttribute("positions", positions);
        model.addAttribute("departments", departments);

        return "staff/stafflist";
    }

    @GetMapping("/staffedit/{id}")
    @PreAuthorize("hasAuthority('PERMISSION_STAFF_EDIT')")
    public String editStaff(@PathVariable("id") Integer id, Model model, @SessionAttribute("user") PermissionUser user) {
        GardenStaffInfo staff = gardenStaffInfoService.findById(id);
        Map<String, Object> paramMap = new HashMap<String, Object>(16);
        paramMap.put("gardenId", user.getGardenId());
        List<GardenStudentState> states = stateService.getStudentStateList(paramMap);
        List<SysRole> roles = roleService.getRoleList(paramMap);
        List<GardenStaffPosition> positions = positionService.getPositionList(paramMap);
        List<GardenDepartment> departments = deptService.getDepartmentList(paramMap);
        Map<String, List<GardenStudentState>> propStates = states.stream().collect(Collectors.groupingBy(GardenStudentState::getStateProp));
        SysUser currentUser = userService.findUserById(staff.getUserId());
        model.addAttribute("invalid", propStates.get("无效学员"));
        model.addAttribute("valid", propStates.get("有效学员"));
        model.addAttribute("member", propStates.get("会员"));
        model.addAttribute("roles", roles);
        model.addAttribute("positions", positions);
        model.addAttribute("departments", departments);
        model.addAttribute("staff", staff);
        model.addAttribute("currentUser", currentUser);


        return "staff/staffedit";
    }

    @GetMapping("/staffview/{id}")
    @PreAuthorize("hasAuthority('PERMISSION_STAFF_VIEW')")
    public String viewStaff(@PathVariable("id") Integer id, Model model, @SessionAttribute("user") PermissionUser user) {
        GardenStaffInfo staff = gardenStaffInfoService.findById(id);

        Map<String, Object> paramMap = new HashMap<String, Object>(16);
        paramMap.put("gardenId", user.getGardenId());
        List<GardenStudentState> states = stateService.getStudentStateList(paramMap);
        List<SysRole> roles = roleService.getRoleList(paramMap);
        List<GardenStaffPosition> positions = positionService.getPositionList(paramMap);
        List<GardenDepartment> departments = deptService.getDepartmentList(paramMap);
        Map<String, List<GardenStudentState>> propStates =
                states.stream().collect(Collectors.groupingBy(GardenStudentState::getStateProp));
        SysUser currentUser = userService.findUserById(staff.getUserId());
        model.addAttribute("invalid", propStates.get("无效学员"));
        model.addAttribute("valid", propStates.get("有效学员"));
        model.addAttribute("member", propStates.get("会员"));
        model.addAttribute("roles", roles);
        model.addAttribute("positions", positions);
        model.addAttribute("departments", departments);
        model.addAttribute("staff", staff);
        model.addAttribute("currentUser", currentUser);

        return "staff/staffview";
    }

    @GetMapping("/staffadd")
    @PreAuthorize("hasAuthority('PERMISSION_STAFF_ADD')")

    public String addStaff(HttpServletRequest request, Model model, @SessionAttribute("user") PermissionUser user) {
        Map<String, Object> paramMap = new HashMap<String, Object>(16);
        paramMap.put("gardenId", user.getGardenId());

        List<GardenStudentState> states = stateService.getStudentStateList(paramMap);
        List<SysRole> roles = roleService.getRoleList(paramMap);
        List<GardenStaffPosition> positions = positionService.getPositionList(paramMap);
        List<GardenDepartment> departments = deptService.getDepartmentList(paramMap);
        Map<String, List<GardenStudentState>> propStates =
                states.stream().collect(Collectors.groupingBy(GardenStudentState::getStateProp));
        model.addAttribute("invalid", propStates.get("无效学员"));
        model.addAttribute("valid", propStates.get("有效学员"));
        model.addAttribute("member", propStates.get("会员"));
        model.addAttribute("roles", roles);
        model.addAttribute("positions", positions);
        model.addAttribute("departments", departments);
        return "staff/staffadd";
    }

    @PostMapping("/stafflist")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STAFF')")
    public Map<String, ?> staffList(String param, StaffInfoSearchVm searchVm, @SessionAttribute("user") PermissionUser user) {

        Map<String, Object> paramMap = DataTableUtils.parseParam(param);
        if (paramMap == null) {
            return RenderJSON.makeMap(-1, "参数不合法！", null, "");
        }
        String sEcho = (String) paramMap.get("sEcho");
        String sSearch = (String) paramMap.get("sSearch");
        int iDisplayStart = (int) paramMap.get("iDisplayStart");
        int iDisplayLength = (int) paramMap.get("iDisplayLength");

        paramMap.clear();
        paramMap.put("search", sSearch);
        paramMap.put("start", iDisplayStart);
        paramMap.put("limit", iDisplayLength);
        paramMap.put("gardenId", user.getGardenId());
        if (searchVm.getStaffDepartment()!=null&&searchVm.getStaffDepartment()>0){
            paramMap.put("staffDepartment",searchVm.getStaffDepartment());
        }
        if (searchVm.getStaffState()!=null&&searchVm.getStaffState()>0){
            paramMap.put("staffState",searchVm.getStaffState());
        }
        if (searchVm.getStaffPosition()!=null&&searchVm.getStaffPosition()>0){
            paramMap.put("staffPosition",searchVm.getStaffPosition());
        }
        if (StringUtils.isNotBlank(searchVm.getStaffPhone())){
            paramMap.put("staffPhone",searchVm.getStaffPhone());
        }
        if (StringUtils.isNotBlank(searchVm.getStaffRealName())){
            paramMap.put("search",searchVm.getStaffRealName());
        }
        List<GardenStaffInfo> staffList = gardenStaffInfoService.getStaffList(paramMap);
        
        List<GardenStaffInfoVo> staffInfoVos=staffList.stream().map(staff->{
            GardenStaffInfoVo staffInfoVo=new GardenStaffInfoVo();
            SysUser sysUser=userService.findUserById(staff.getUserId());
            GardenStaffPosition position=positionService.findById(staff.getStaffPosition());
            GardenDepartment department=deptService.findById(staff.getStaffDepartment());
            SysRole role=roleService.findRoleById(Integer.parseInt(staff.getStaffPermission()));

            staffInfoVo.setUserName(sysUser.getUserName());
            staffInfoVo.setStaffRealName(staff.getStaffRealName());
            staffInfoVo.setStaffDepartment(department.getDeptName());
            staffInfoVo.setStaffPosition(position.getPositionName());
            staffInfoVo.setStaffPhone(staff.getStaffPhone());
            staffInfoVo.setIsAdviser(staff.getIsAdviser());
            staffInfoVo.setIsMarketPerson(staff.getIsMarketPerson());
            staffInfoVo.setIsTeacher(staff.getIsTeacher());
            staffInfoVo.setStaffPermission(role.getRoleName());
            staffInfoVo.setStaffState(staff.getStaffState());
            staffInfoVo.setId(staff.getId());

            return staffInfoVo;
        }).collect(Collectors.toList());
        Integer count = gardenStaffInfoService.getStaffCount(paramMap);

        return RenderJSON.makePagenateMap(1, "获取成功", sEcho, count, count, staffInfoVos, "");
    }

    @PostMapping("/staffadd")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STAFF_ADD')")
    @Transactional(rollbackFor = Exception.class)
    public Map<String, ?> addStaff(@RequestBody @Valid GardenStaffInfoVm staffVm, @SessionAttribute("user") PermissionUser user) {

        GardenStaffInfo staff = new GardenStaffInfo();
        staff.setStaffEmail(staffVm.getStaffEmail());
        staff.setStaffRealName(staffVm.getStaffRealName());
        staff.setStaffState(staffVm.getStaffState());
        staff.setStaffPhone(staffVm.getStaffPhone());
        staff.setStaffJoinTime(staffVm.getStaffJoinTime());
        staff.setStaffDepartment(staffVm.getStaffDepartment());
        staff.setStaffQq(staffVm.getStaffQq());
        staff.setStaffPosition(staffVm.getStaffPosition());
        staff.setIsAdviser(staffVm.getIsAdviser() == null ? 0 : staffVm.getIsAdviser());
        staff.setIsTeacher(staffVm.getIsTeacher() == null ? 0 : staffVm.getIsTeacher());
        staff.setIsMarketPerson(staffVm.getIsMarketPerson() == null ? 0 : staffVm.getIsMarketPerson());
        staff.setStaffPermission(staffVm.getStaffPermission());
        staff.setHasStudent(staffVm.getHasStudent());
        staff.setStaffRemark(staffVm.getStaffRemark());
        staff.setCreateTime(new Date());
        staff.setUpdateTime(new Date());
        staff.setGardenId(user.getGardenId());


        //创建该员工登录系统的账号
        SysUser logInUser = new SysUser();

        logInUser.setUserName(staffVm.getUserName());
        logInUser.setUserRealName(staffVm.getStaffRealName());
        logInUser.setUserPhone(staffVm.getStaffPhone());
        logInUser.setGardenId(user.getGardenId());
        //默认登录密码为手机号码
        logInUser.setUserPassword(bCryptPasswordEncoder.encode(staffVm.getStaffPhone()));
        logInUser.setUpdateTime(new Date());
        logInUser.setUserRegisterTime(new Date());
        //将登录用户插入数据库
        userService.saveUser(logInUser);
        //创建登录用户和角色的对应关系
        SysRoleUser roleUser = new SysRoleUser();
        roleUser.setRoleId(Integer.parseInt(staffVm.getStaffPermission()));
        roleUser.setUserId(logInUser.getId());
        roleUser.setCreateTime(new Date());
        roleUser.setUpdateTime(new Date());
        roleUserService.save(roleUser);

        staff.setUserId(logInUser.getId());
        Integer result = gardenStaffInfoService.save(staff);

        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，添加成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，添加失败！", "error");
        }

    }

    @DeleteMapping("/staffdelete/{id}")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STAFF_DELETE')")
    @Transactional(rollbackFor = Exception.class)
    public Map<String, ?> deleteStaff(@SessionAttribute("user") PermissionUser user, @PathVariable("id") Integer id) {

        GardenStaffInfo staffInfo = gardenStaffInfoService.findById(id);
        if (staffInfo == null) {
            return RenderJSON.makeStandMap(2, "对不起，该员工不存在，删除失败！", "error");
        }
        if (!user.getGardenId().equals(staffInfo.getGardenId())) {
            return RenderJSON.makeStandMap(2, "对不起，您不具备删除权限，请联系管理员！", "ok");
        }

        //删除该用户的登录账号
        userService.delete(staffInfo.getUserId());

        Integer result = gardenStaffInfoService.delete(id);
        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，删除成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，删除失败！", "error");
        }

    }

    @PostMapping("/staffedit/{id}")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STAFF_EDIT')")
    public Map<String, ?> editStaff(@PathVariable("id") Integer id, @RequestBody @Valid GardenStaffInfoVm staffVm, @SessionAttribute("user") PermissionUser user) {

        GardenStaffInfo staff = gardenStaffInfoService.findById(id);
        if (!user.getGardenId().equals(staff.getGardenId())) {
            return RenderJSON.makeStandMap(2, "对不起，您不具备修改权限，请联系管理员！", "ok");
        }
        staff.setId(id);
        staff.setStaffEmail(staffVm.getStaffEmail());
        staff.setStaffRealName(staffVm.getStaffRealName());
        staff.setStaffState(staffVm.getStaffState());
        staff.setStaffPhone(staffVm.getStaffPhone());
        staff.setStaffJoinTime(staffVm.getStaffJoinTime());
        staff.setStaffDepartment(staffVm.getStaffDepartment());
        staff.setStaffQq(staffVm.getStaffQq());
        staff.setStaffPosition(staffVm.getStaffPosition());
        staff.setIsAdviser(staffVm.getIsAdviser() == null ? 0 : staffVm.getIsAdviser());
        staff.setIsTeacher(staffVm.getIsTeacher() == null ? 0 : staffVm.getIsTeacher());
        staff.setIsMarketPerson(staffVm.getIsMarketPerson() == null ? 0 : staffVm.getIsMarketPerson());
        staff.setStaffPermission(staffVm.getStaffPermission());
        staff.setHasStudent(staffVm.getHasStudent());
        staff.setStaffRemark(staffVm.getStaffRemark());

        staff.setUpdateTime(new Date());

        //创建该员工登录系统的账号
        SysUser logInUser = userService.findUserById(staff.getUserId());
        logInUser.setUserRealName(staffVm.getStaffRealName());
        logInUser.setUserPhone(staffVm.getStaffPhone());
        logInUser.setGardenId(user.getGardenId());
        //默认登录密码为手机号码
        logInUser.setUpdateTime(new Date());
        //将登录用户插入数据库
        userService.saveUser(logInUser);
        //创建登录用户和角色的对应关系

        SysRoleUser roleUser = roleUserService.findByUserId(logInUser.getId());
        roleUser.setRoleId(Integer.parseInt(staffVm.getStaffPermission()));
        roleUser.setUserId(logInUser.getId());
        roleUser.setCreateTime(new Date());
        roleUser.setUpdateTime(new Date());
        roleUserService.save(roleUser);

        staff.setUserId(logInUser.getId());

        Integer result = gardenStaffInfoService.save(staff);
        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，编辑成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }
    }
}
